package com.example.demo.dao.impl;


import com.example.demo.dao.GonggaoDao;
import com.example.demo.model.Gonggao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Repository
@Transactional(rollbackFor = Exception.class)
public class GonggaoDaoImpl  implements GonggaoDao {

    @Autowired
    HibernateTemplate hibernateTemplate;

    @Override
    public void deleteBean(Gonggao bean) {
       hibernateTemplate.delete(bean);

    }

    @Override
    public void insertBean(Gonggao bean) {
       hibernateTemplate.save(bean);

    }

    @Override
    @SuppressWarnings("unchecked")
    public Gonggao selectBean(String where) {
        List<Gonggao> list = (List<Gonggao>)hibernateTemplate.find("from Gonggao " + where);
        if (list.size() == 0) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public int selectBeanCount(String where) {
        long count = (Long)hibernateTemplate.find("select count(*) from Gonggao " + where).get(0);
        return (int) count;
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Gonggao> selectBeanList(final int start, final int limit, final String where) {
        return (List<Gonggao>)hibernateTemplate.executeWithNativeSession((HibernateCallback) session -> {
            List<Gonggao> list = session.createQuery("from Gonggao " + where)
                    .setFirstResult(start)
                    .setMaxResults(limit)
                    .list();
            return list;
        });

    }

    @Override
    public void updateBean(Gonggao bean) {
       hibernateTemplate.update(bean);

    }


}
